<template>
  <div>
    <!--  轮播图  -->
    <div style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);border-radius: 4px">
      <el-carousel indicator-position="outside">
        <el-carousel-item v-for="item in photo" :key="item">
          <img :src="item" height="100%" width="100%" alt="for photo">
        </el-carousel-item>
      </el-carousel>
    </div>
    <!-- 提示 -->
    <span style="color: gray;">注意：图片来源为百度图片搜索，与此项目并无直接关系，仅作为参考，欢迎随时投递图片，有需要，请联系成江大大~~</span>
    <!-- main -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="16"><div class="grid-content bg-purple">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>展示任务</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="dialogFormVisible1=true">点我发布任务？</el-button>
          </div>
          <div class="infinite-list-wrapper" style="overflow:auto">
            <ul
              class="list"
              v-infinite-scroll="load"
              infinite-scroll-disabled="disabled">
              <div v-for="item in tableData" :key="item.id">
                <el-card shadow="hover" style="padding: 5px; margin-bottom: 5px">
                  <el-row :gutter="20">
                    <el-col :span="16"><div class="grid-content bg-purple">
                      <el-tag>{{item.name}}</el-tag>
                      <el-button @click.native.prevent="getDetails(item.creator, item.id)" style="float: right; padding: 3px 0" type="text">点击查看发布者信息，方便您即使沟通</el-button>
                      <el-divider></el-divider>
                      <div>{{ item.content.substr(0, 10)+'...' }}</div>
                      <span style="color: darkgray; font-size: 15px">发布时间：{{ timestampToTime(item.createTime) }}</span>|
                      <span style="color: darkgray; font-size: 15px">截止时间：{{ timestampToTime(item.deadline) }}</span>
                    </div></el-col>
                    <el-col :span="8"><div class="grid-content bg-purple">
                      <div>参考图片</div>
                      <div>
                        <el-image
                          style="width: 100%; height: 100px"
                          :src="url"
                          :preview-src-list="srcList">
                        </el-image>
                      </div>
                      <div>报酬 <span style="color: orangered;">{{ item.reward }}</span> 元</div>
                    </div></el-col>
                  </el-row>
                </el-card>
              </div>
            </ul>
            <p style="margin: auto" v-if="loading">加载中...</p>
            <div v-if="noMore">
              <el-empty description="哎呀，人家也是有底线的呀~~~"></el-empty>
            </div>
          </div>
        </el-card>
      </div></el-col>
      <el-col :span="8"><div class="grid-content bg-purple">
        <el-card shadow="hover" style="margin-bottom: 20px">
          <div slot="header" class="clearfix">
            <span>常用任务类型</span>
          </div>
          <div>
            <el-tag style="margin: 5px">代取外卖</el-tag>
            <el-tag style="margin: 5px">代课</el-tag>
            <el-tag style="margin: 5px">代取快递</el-tag>
            <el-tag style="margin: 5px">卖书不</el-tag>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>新闻新闻新闻~</span>
          </div>
          <div v-for="item in tableData4news" :key="item.id" class="text item">
            <el-button style="width: 100%;text-align: left" @click.native.prevent="getNewsDetail(item.id)">
              <strong>{{ item.newsTitle.substr(0, 5)+'...' }}</strong>
              <el-divider direction="vertical"></el-divider>
              <span style="color: darkgray">time: {{ timestampToTime(item.createTime) }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span style="color: darkgray">浏览量 <i style="color: darkgray" class="el-icon-view"></i>&nbsp;&nbsp;&nbsp;&nbsp; {{ item.views }}</span>
            </el-button>
          </div>
          <el-button style="text-align:center;width: 100%" class="load-more mr-bottom" v-if="this.pageSize4news<this.pageTotal4news"  @click='loadMore' >点击加载更多</el-button>
          <div class="load-more mr-bottom" v-else ><el-empty description="哎呀，人家也是有底线的呀~~~"></el-empty></div>
        </el-card>

      </div></el-col>
    </el-row>
    <!--  查看详细信息并接收任务：  -->
    <el-dialog v-dialog-drag title="发布者信息查看" :visible.sync="dialogFormVisible">
      <div>
        <el-form :model="userData" ref="userForm" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input :disabled="true" clearable="clearable" v-model="userData.username"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName" required>
            <el-input :disabled="true" clearable="clearable" v-model="userData.realName"></el-input>
          </el-form-item>
          <el-form-item label="您的联系电话" prop="tel">
            <el-input :disabled="true" type="number" clearable="clearable" v-model="userData.tel"></el-input>
          </el-form-item>
          <el-form-item label="您的联系QQ" prop="qq">
            <el-input :disabled="true" type="number" clearable="clearable" v-model="userData.qq"></el-input>
          </el-form-item>
          <el-form-item label="您的寝室" prop="bedroomAddr" required>
            <el-input :disabled="true" clearable="clearable" v-model="userData.bedroomAddr"></el-input>
          </el-form-item>
          <el-form-item label="介绍" prop="remark">
            <el-input :disabled="true" type="textarea" v-model="userData.remark"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="acceptTask">接收任务</el-button>
      </div>
    </el-dialog>
    <!--   首页发布任务   -->
    <el-dialog v-dialog-drag title="发布任务" :visible.sync="dialogFormVisible1">
      <div>
        <el-form :model="taskForm1" ref="taskForm1" label-width="100px">
          <el-form-item label="是否自定义" prop="isSelfTask">
            <el-switch v-model="taskForm1.isSelfTask"></el-switch>
          </el-form-item>
          <el-form-item label="任务名称" prop="name">
            <el-input clearable="clearable" v-if="taskForm1.isSelfTask" v-model="taskForm1.name"></el-input>
            <el-select clearable="clearable" v-else v-model="taskForm1.name" placeholder="任务类型">
              <el-option label="代课" value="代课"></el-option>
              <el-option label="代取快递" value="代取快递"></el-option>
              <el-option label="代取外卖" value="代取外卖"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任务时间" required>
            <el-date-picker
              v-model="taskForm1.start2endTime"
              type="datetimerange"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd hh:mm:ss"
              :formatter="dateFormat"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="是否紧急" prop="isUrgent">
            <el-switch v-model="taskForm1.isUrgent"></el-switch>
          </el-form-item>
          <el-form-item label="任务报酬" prop="reward">
            <el-input type="number" clearable="clearable" v-model="taskForm1.reward"></el-input>
          </el-form-item>
          <el-form-item label="任务描述" prop="content">
            <el-input type="textarea" v-model="taskForm1.content"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {accept, getTask} from "@/api/task";
import {getDetails} from "@/api/user";
import {getNews} from "@/api/news";
import store from "@/store";
export default {
  name: "home",
  data(){
    return {
      // current task id
      curTid: '',
      // 查看详情：
      dialogFormVisible: false,
      dialogFormVisible1: false,
      //
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      pageTotal: 10,
      // news:
      pageNum4news: 1,
      pageSize4news: 10,
      pageTotal4news: 10,
      tableData4news: [],
      taskForm: {
        name: '',
        isUrgent: 0,
        createTime: '',
        content: '',
        isDeal: 0,
        reward: 100,
        creator: '',
        deadline: '',
        remark: '-',
        imgUrl: 'easy-help/upload/file/img/'
      },
      // 发布任务：
      taskForm1: {
        name: '',
        isUrgent: 0,
        start2endTime: [],
        createTime: '',
        content: '',
        isdeal: 0,
        reward: 100,
        creator: '',
        deadline: '',
        remark: '-',
        imgUrl: 'easy-help/upload/file/img/'
      },
      photo: [
        require('../assets/img/forJava.jpeg'),
        require('../assets/img/forGOlang.jpeg'),
        require('../assets/img/zhiyuan2.jpeg'),
        require('../assets/img/zhiyuanJob.jpeg')
      ],
      url: require('../assets/img/forJava.jpeg'),
      srcList: [
        require('../assets/img/forGOlang.jpeg'),
        require('../assets/img/zhiyuan2.jpeg'),
        require('../assets/img/zhiyuanJob.jpeg')
      ],
      // user data:
      userData: {
        id: '',
        bedroomAddr: "",
        qq: '',
        realName: '',
        remark: "",
        reputation: 100,
        role: "-",
        tel: 13900000000,
        username: "-",
      },
      // loading for data
      loading: false
    }
  },
  computed: {
    noMore () {
      return this.pageSize >= this.pageTotal
    },
    disabled () {
      return this.loading || this.noMore
    }
  },
  methods: {
    async acceptTask(){
      // get user
      store.dispatch('user/getInfo').then(data => {
        if (data.reputation < 80){
          this.$notify({
            title: '失败',
            message: '抱歉，您的信誉分低于80，不能接收任务',
            type: 'error'
          });
        }else{
          // ====================================================
          this.acceptMethod()
          this.loading = true
        }
      })
      this.loading = false
    },
    async acceptMethod(){
      const response = await accept(this.curTid, this.userData.id)
      console.log('我接受了任务', response)
      if (response.code === 200){
        this.$notify({
          title: '接收任务成功',
          message: '请到个人信息去查看任务叭',
          type: 'success'
        });
        this.loading = false
      }else{
        this.$notify({
          title: '接收失败',
          message: '该任务已被其他人接收了噢~~~',
          type: 'error'
        });
        this.loading = false
      }
    },
    async getTasks() {

      // this.taskForm['pageNum'] = this.pageNum
      // this.taskForm['pageSize'] = this.pageSize
      const response = await getTask({pageNum: this.pageNum, pageSize: this.pageSize})
      console.log('home page here: ', response)
      this.tableData = response.data.list
      this.pageTotal = response.data.total
      console.log('home page here: ', this.tableData)
    },
    async getNewsDetail(id){
      await this.$router.push({
        path:'/main/news-detail/'+id,
      })
    },
    async getDetails(id, curTid){
      this.dialogFormVisible = true
      const response = await getDetails(id)
      this.userData = response.data
      this.curTid = curTid
      console.log(curTid,response.data)
    },
    timestampToTime (timestamp) {
      var date = new Date(timestamp) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
      var D = date.getDate() + ' '
      var h = date.getHours() + ':'
      var m = date.getMinutes() + ':'
      var s = date.getSeconds()
      return Y+M+D+h+m+s
    },
    load () {
      this.loading = true
      setTimeout(() => {
        this.pageSize += 2
        this.getTasks()
        this.loading = false
      }, 2000)
    },
    // for news:
    async getNews() {
      const response = await getNews(this.pageNum4news, this.pageSize4news)
      console.log('this the news：',response)
      this.pageNum4news = response.data.pageNum
      this.pageSize4news = response.data.pageSize
      this.pageTotal4news = response.data.total
      this.tableData4news = response.data.list
    },
    loadMore:function(){
      this.pageSize4news+=5; // 每次加载5条
      this.getNews()
    },
    submitForm() {
      this.$refs.taskForm1.validate((valid) => {
        if (valid) {
          if (this.taskForm1.isDeal) {
            this.taskForm1.isDeal = 1
          }else{
            this.taskForm1.isDeal = 0
          }
          if (this.taskForm1.isUrgent) {
            this.taskForm1.isUrgent = 1
          }else{
            this.taskForm1.isUrgent = 0
          }
          this.taskForm1.createTime = this.taskForm1.start2endTime[0]
          this.taskForm1.deadline = this.taskForm1.start2endTime[1]
          // get user
          store.dispatch('user/getInfo').then(data => {
            //
            this.taskForm1.creator = data.id
            if (data.reputation < 80){
              this.$notify({
                title: '任务发布失败',
                message: '抱歉，您的信誉分低于60，不能进行发布任务',
                type: 'error'
              });
            }else{
              this.$store.dispatch('task/create', this.taskForm1)
                .then(() => {
                  this.dialogFormVisible1 = false
                  this.$notify({
                    title: '任务发布成功',
                    message: '请到个人信息去查看任务叭',
                    type: 'success'
                  });
                  this.$router.push('/main/home')
                })
                .catch(() => {
                  this.loading = false
                })
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    dateFormat(row, column, cellValue, index) {
      console.log(row, column, cellValue, index)
      const daterc = row[column.property]
      if (daterc != null) {
        var date = new Date(daterc);
        var year = date.getFullYear();
        /* 在日期格式中，月份是从0开始，11结束，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // 拼接
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
      }
    }
  },
  mounted() {
    this.getTasks()
    // loading the news here:
    this.getNews()
  },
}
</script>

<style lang="scss">
.el-carousel__item h3 {
  color: #475669;
  font-size: 18px;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}

/* about news here */

</style>
